package com.haiyi.software.app.basic;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.haiyi.software.app.R;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

public abstract class ActivityBasicCharmCityList extends ActivityBasic {

	private final String TAG = "ActivityBasicCharmCityList";

	private List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

	protected List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();

	protected String str_server = null;

	private String str_requestName = "productList.php";

	@Override
	public void requestNetworkData(Object... args) {

		str_server = this.getResources().getString(R.string.URL);

		String str_requestURL = str_server + str_requestName;

		AsyncHttpClient client = new AsyncHttpClient();

		client.post(str_requestURL, responseHandler);
	}

	private AsyncHttpResponseHandler responseHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int statusCode, Header[] headers,
				byte[] responseBody) {

			try {
				String str_jsonReturn = new String(responseBody, "UTF-8");

				JsonParser parser = new JsonParser();

				JsonObject json_return = parser.parse(str_jsonReturn)
						.getAsJsonObject();

				if (json_return.get("state").getAsString().equals("200")) {

					putDateToList(json_return.get("body").getAsJsonObject()
							.get("productList").getAsJsonArray());

				}

			} catch (Exception e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}

			requestFinish(null);
		}

		@Override
		public void onFailure(int statusCode, Header[] headers,
				byte[] responseBody, Throwable error) {
			// TODO 自动生成的方法存根
			requestFinish(null);
		}
	};

	private void putDateToList(JsonArray asJsonArray) {
		// TODO 自动生成的方法存根

		Gson gson = new Gson();

		Type type = new TypeToken<Map<String, String>>() {
		}.getType();

		list.clear();

		for (JsonElement jsonElement : asJsonArray) {

			Map<String, Object> map = gson.fromJson(jsonElement, type);

			list.add(map);
		}

		data.clear();

		data.addAll(list);
	}
}
